package com.xingchi.tornado.core.filter;

import com.xingchi.tornado.unique.provider.impl.UUIDProvider;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

import static com.xingchi.tornado.core.constants.Constants.MDC_TRACE_ID;


/**
 * traceId过滤器，通过Sli4j提供的MDC实现分布式链路追踪
 *
 * @author xingchi
 * @date 2024/5/30 8:43
 */
@Component
public class TraceFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        try {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            String traceId = httpServletRequest.getHeader(MDC_TRACE_ID);
            if (StringUtils.isBlank(traceId)) {
                traceId = getTraceId();
            }
            MDC.put(MDC_TRACE_ID, traceId);
            chain.doFilter(request, response);
        } finally {
            MDC.remove(MDC_TRACE_ID);
        }

    }

    public String getTraceId() {
        return UUID.randomUUID().toString().replace("-", "");
    }

}
